<script setup>
import { ref } from 'vue'
import PageContainer from '../../components/PageContainer.vue'
import { myUpdatePwdService } from '@/api/user'

const defaultPwdForm = {
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
}
const formRef = ref()
const pwdForm = ref({ ...defaultPwdForm })
const loading = ref(false)

const validateLength = (rule, value, callback) => {
  if (!value || value.length < 6 || value.length > 15) {
    callback(new Error('请输入6-15位密码'))
  } else {
    callback()
  }
}

const validateNewPwd = (rule, value, callback) => {
  if (!value || value.length < 6 || value.length > 15) {
    callback(new Error('请输入6-15位密码'))
  } else if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能和原密码相同'))
  } else {
    callback()
  }
}

const validateConfirmPwd = (rule, value, callback) => {
  if (!value || value.length < 6 || value.length > 15) {
    callback(new Error('请输入6-15位密码'))
  } else if (value !== pwdForm.value.new_pwd) {
    callback(new Error('确认密码必须与新密码一致'))
  } else {
    callback()
  }
}

const rules = {
  old_pwd: [{ required: true, validator: validateLength, trigger: 'blur' }],
  new_pwd: [{ required: true, validator: validateNewPwd, trigger: 'blur' }],
  re_pwd: [{ required: true, validator: validateConfirmPwd, trigger: 'blur' }]
}

const onSubmit = async () => {
  loading.value = true
  try {
    await formRef.value.validate() // 如果验证失败会抛异常
    const res = await myUpdatePwdService(pwdForm.value)
    if (res.code === 0) {
      ElMessage.success('密码修改成功')
      formRef.value.resetFields()
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (error) {
    // 校验失败 或 接口错误 会走这里
    // 你可以根据需要 log 出 error
    if (error instanceof Error) {
      console.warn('表单验证或接口错误:', error.message)
    }
  } finally {
    loading.value = false
  }
}

const onReset = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <PageContainer title="修改密码">
    <el-form
      v-loading="loading"
      :model="pwdForm"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password" show-password />
      </el-form-item>

      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password" show-password />
      </el-form-item>

      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">修改密码</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
